//
//  JokeTableViewController.m
//  BobNews
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 YJC. All rights reserved.
//

#import "JokeTableViewController.h"
#import "NetWorkRequestManager.h"
#import "CycleView.h"
#import "LORefresh.h"
#import "ToutiaoPhotoViewController.h"


#import "ToutiaoModel.h"
#import "ToutiaoModelCell.h"
#import "ToutiaoImageModelCell.h"
#import "ToutiaoMulImgModelCell.h"

#import "ToutiaoArticleViewController.h"
#import "ToutiaoSpeciaTableController.h"
#import "ToutiaoPhotoViewController.h"

@interface JokeTableViewController ()
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) CycleView *cycleView;
@property (nonatomic,strong) NSString *start;

@end

@implementation JokeTableViewController

-(void)dealloc{
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.start = @"0";
    
    self.dataArray = [NSMutableArray new];
    
    [self dataLoad];
    
    
    /// 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"ToutiaoImageModelCell" bundle:nil] forCellReuseIdentifier:@"ToutiaoImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ToutiaoMulImgModelCell" bundle:nil] forCellReuseIdentifier:@"ToutiaoMulImgModel"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableHeaderView = self.cycleView;
    
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.dataArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf dataLoad];
        
    }];
    
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.dataArray.count;
        
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf dataLoad];

        
    }];
    
    
    self.cycleView = [[CycleView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 200) interVal:2];
    self.tableView.tableHeaderView = self.cycleView;
}

-(void)dataLoad{
    
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:@"http://c.3g.163.com/nc/article/list/T1368497029546/0-20.html"] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);


        NSDictionary *Josndict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *listDict in Josndict[@"T1368497029546"]) {
            ToutiaoModel *model = [ToutiaoModel modelWithDictionary:listDict];
            [self.dataArray addObject:model];
        }
        
        NSArray *array = Josndict[@"T1368497029546"];
        NSString *imgStr = array[0][@"imgsrc"];
        NSMutableArray *mArray = [NSMutableArray array];
        [mArray addObject:imgStr];
        NSArray *imgArray = array[0][@"imgextra"];
        for (NSDictionary *imgsrcDict in imgArray) {
            [mArray addObject:imgsrcDict[@"imgsrc"]];
        }
        
        
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            self.cycleView.imgNameArray = mArray;
            
            [[self.tableView defaultHeader]endRefreshing];
            [[self.tableView defaultFooter]endRefreshing];
            
        });
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [ToutiaoModelCell cellWithTableView:tableView Model:self.dataArray[indexPath.row] IndexPath:indexPath];
    
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *modelName = NSStringFromClass([self.dataArray[indexPath.row] class]);
    Class CellClass = NSClassFromString([modelName stringByAppendingString:@"Cell"]);
    
    return [CellClass height];

    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
//        JokeViewController *jockVC = [[JokeViewController alloc]init];
//        jockVC.urlStr = [self.dataArray[indexPath.row] url_3w];
//        [self.navigationController pushViewController:jockVC animated:YES];

    ToutiaoModel *model = self.dataArray[indexPath.row];
    
    NSString *special = model.specialID;
    NSString *photo = model.photosetID;
    NSString *reSource = model.recSource;
    //    NSString *tag = model.TAG;
    //    NSString *video = model.videoID;
    if (special) {
        ToutiaoSpeciaTableController *specialTVC = [[ToutiaoSpeciaTableController alloc]init];
        specialTVC.specialID = model.specialID;
        specialTVC.navTitle = model.title;
        [self.navigationController pushViewController:specialTVC animated:YES];
    } else if (photo || [reSource isEqualToString:@"图集"]) {
        ToutiaoPhotoViewController *photoVC = [[ToutiaoPhotoViewController alloc]init];
        photoVC.navTitle = model.title;
        photoVC.photosetID = model.photosetID;
        NSLog(@"%@",model.photosetID);
        [self presentViewController:photoVC animated:YES completion:^{
            
        }];
    }
    //    else if (video) {
    //
    //    }
    //    else if ([tag isEqualToString:@"直播预告"] || [tag isEqualToString:@"正在直播"]) {
    //
    //    }
    else {
        ToutiaoArticleViewController *articalVC = [[ToutiaoArticleViewController alloc]init];
        articalVC.docid = model.docid;
        articalVC.navTitle = model.title;
        articalVC.model = model;
        [self.navigationController pushViewController:articalVC animated:YES];
    }

    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
